package com.dys.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: 疾风
 * @ClassName: Filter1_LoginFilter
 * @Description: 登录过滤器
 * @CreateDate: 2024/09/25
 * @Version: v1.0.0
 */
@WebFilter(urlPatterns = "/*")// 任何资源都要过滤
public class Filter1_LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("执行Filter1_LoginFilter的init()方法......");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 无论是否登录，都需要放行
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String requestURI = httpServletRequest.getRequestURI();
        System.out.println("请求的资源：" + requestURI);
        // 无论是否登录过,都要放行的资源   登录页  登录校验Controller 和一些静态资源
        if (requestURI.contains("login.jsp") || requestURI.contains("loginServlet.do") || requestURI.contains("/static/")) {
            // 直接放行
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            // 后续代码不再执行
            return;
        }
        // 需要登录之后才能访问的资源,如果没登录,重定向到login.jsp上,提示用户进行登录
        Object user = httpServletRequest.getSession().getAttribute("user");
        if (null != user) {
            // 登录过,放行
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } else {
            // 未登陆过，跳转到登录页
            httpServletResponse.sendRedirect("login.jsp");
        }
    }

    @Override
    public void destroy() {
        System.out.println("执行Filter1_LoginFilter的destroy()方法......");
    }
}
